//
//  TouchDrawView.m
//  KEREN
//
//  Created by MW on 2023/3/10.
//

#import "TouchDrawView.h"

@implementation TouchDrawView


- (instancetype)initWithFrame:(CGRect)frame
{
 self = [super initWithFrame:frame];
 if (self) {
     self.backgroundColor = [UIColor blackColor];
 [self setUp];
 }
 return self;
}

// 重绘UI
- (void)drawRect:(CGRect)rect {

// for (UIBezierPath* path in self.drawPath) {

 if ([self.drawPath isKindOfClass:[UIImage class]]) {
  // 画图片
  UIImage* image = (UIImage*)self.drawPath;
  [image drawInRect:rect];
 }else{
  // 画线

  // 设置画笔颜色
  [[UIColor redColor] set];

  // 绘制
  [self.drawPath stroke];
 }
 
}
//- (NSMutableArray*)paths{
//
// if (_paths == nil) {
// _paths = [NSMutableArray array];
// }
// return _paths;
//}
//
// 重写image属性
- (void)setImage:(UIImage *)image{

 _image = image;

 // 将图片加入到线条数组中
 //[self.paths addObject:image];

 [self setNeedsDisplay];
}

#pragma mark - Init

// 初始化
- (void)setUp{

 // 添加平移手势
 UIPanGestureRecognizer* panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
 [self addGestureRecognizer:panGes];

 // 默认值
 self.lineWidth = 5;
 self.pathColor = [UIColor redColor];
}

- (void)panGes:(UIPanGestureRecognizer*)ges{

 // 获取当前点
 CGPoint curPoint = [ges locationInView:self];

 if (ges.state == UIGestureRecognizerStateBegan) { // 开始移动

 // 创建贝塞尔曲线
    _drawPath = [[UIBezierPath alloc]init];

 // 设置线条宽度
     _drawPath.lineWidth = _lineWidth;

 // 线条默认颜色
    // _drawPath.pathColor = _pathColor;

 // 设置起始点
 [_drawPath moveToPoint:curPoint];

 // [self.paths addObject:_path];
 }else if (ges.state == UIGestureRecognizerStateEnded){ //绘画结束
     UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);

      // 获取当前上下文
      CGContextRef context = UIGraphicsGetCurrentContext();

      // 渲染图层到上下文
      [self.layer renderInContext:context];

      // 从上下文中获取图片
      UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

      // 关闭上下文
      UIGraphicsEndImageContext();
     [[LoginManager sharedInstance] mostColor:image scale:0.3];
 }

 // 连线
 [_drawPath addLineToPoint:curPoint];

 // 重绘
 [self setNeedsDisplay];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
